package com.adu.music.spider;

import com.adu.music.parser.MvParser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2017/1/1
 */
public class MvUpdateSpider extends AbstractSpider {

    private int pageIndex = 0;
    private final int pageSize = 100;

    @Override
    protected void initTaskQueue() {
        List<Map<String, Object>> mvs = queryMvsByIndex(pageIndex);
        mvs.forEach(mv -> putTaskToQueue(mv.get("id")));
        pageIndex++;
    }

    private List<Map<String, Object>> queryMvsByIndex(int index) {
        final String sql = "select id from mv limit :offset,:size";
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("offset", pageIndex * pageSize);
        paramMap.put("size", pageSize);
        return asyncNamedParameterJdbcTemplate.queryForList(sql, paramMap);
    }

    @Override
    protected void produceTask() {
        while (!Thread.interrupted()) {
            List<Map<String, Object>> mvs = queryMvsByIndex(pageIndex);
            mvs.forEach(mv -> putTaskToQueue(mv.get("id")));
            if (mvs.size() < pageSize) break;
            pageIndex++;
        }
    }

    @Override
    protected void consumeTask(Object task) {
        String mvId = String.valueOf(task);
        Map<String, Object> mv = MvParser.parseVideo(mvId);
        String sql = "update mv set comment=:comment,updated_at=now() where id=:id";
        if (mv.isEmpty()) return;
        asyncNamedParameterJdbcTemplate.update(sql, mv);
    }
}
